package com.alibaba.otter.node.etl.load.loader.mq.rabbit;

import com.alibaba.otter.node.etl.load.loader.mq.rabbit.namespace.NamespaceManager;
import com.alibaba.otter.shared.common.model.config.data.DataMediaSource;
import com.alibaba.otter.shared.common.model.config.data.mq.RabbitMQMediaSource;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.core.env.StandardEnvironment;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class MqPlugin {
//
//    @Setter(AccessLevel.PACKAGE)
//    private static StandardEnvironment context;

    private static Map<String, PublisherBuilder> pluginMap = new ConcurrentHashMap<>();

    public static MqPlugin init() {

        return new MqPlugin();
        //  return init(context);
    }

//    public static MqPlugin init(StandardEnvironment env) {
//        MqPlugin plugin = new MqPlugin();
//        NamespaceManager.appendConfig(env);
//        return plugin;
//    }

//    public static MqPlugin init(Properties properties) {
//        MqPlugin plugin = new MqPlugin();
//        NamespaceManager.appendConfig(properties);
//        return plugin;
//    }

    public static MqPlugin init(String namespace, Map<String, Object> configs) {
        MqPlugin plugin = new MqPlugin();
        NamespaceManager.appendConfig(namespace, configs);
        return plugin;
    }

    public static MqPlugin init(String namespace, RabbitMQMediaSource dataMediaSource) {
        Map<String, Object> configs = new HashMap<>();
        configs.put("user", dataMediaSource.getUsername());
        configs.put("pwd", dataMediaSource.getPassword());
        configs.put("vhost", dataMediaSource.getVhost());
        configs.put("addrs", dataMediaSource.getUrl().split("//")[1]);
        configs.put("timeout", 5000);
        return init(namespace, configs);
    }

    public PublisherBuilder publisher() {
        return publisher(null);
    }

    public PublisherBuilder publisher(String namespaceName) {
        namespaceName = namespaceName == null ? "" : namespaceName;
        return pluginMap.getOrDefault(namespaceName, new PublisherBuilder(namespaceName));
    }

//    public ListenerBuilder listener() {
//        return listener(null);
//    }
//
//    public ListenerBuilder listener(String namespaceName) {
//        namespaceName = namespaceName == null ? "" : namespaceName;
//        return new ListenerBuilder(namespaceName);
//    }
}
